package controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import DAO.DietDAO;
import DAO.MenuDAO;
import DTO.DietDTO;
import DTO.MenuDTO;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import constants.StringConstants;

/**
 * Servlet implementation class MenuGroupMaintainServlet
 */
public class MenuMaintainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MenuMaintainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			DietDAO dietDAO = new DietDAO();
			ArrayList<DietDTO> dietlist = dietDAO.select();
			request.setAttribute("DIETLIST", dietlist);

			RequestDispatcher rd = request
					.getRequestDispatcher("admin/menu-add.jsp");
			rd.forward(request, response);
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			request.setCharacterEncoding("UTF-8");
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) {
				String action = request.getParameter("action");
				String imgPath = request.getParameter("oldImg");
				// process for deleting
				if (action.equals("delete")) {
					String realPath = getServletContext().getRealPath("/")
							+ imgPath;
					File deletedFile = new File(realPath);
					deletedFile.delete();

					int id = Integer.parseInt(request.getParameter("id"));
					MenuDAO dao = new MenuDAO();
					dao.delete(id);
					response.sendRedirect("MenuServlet");
				} else {
					response.sendRedirect("error.html");
				}
			} else {
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				List items = null;
				try {
					items = upload.parseRequest(request);
				} catch (FileUploadException e) {
					e.printStackTrace();
				}
				Iterator iterator = items.iterator();
				Hashtable params = new Hashtable();
				String filename = null;
				FileItem imgFileItem = null;
				while (iterator.hasNext()) {
					FileItem item = (FileItem) iterator.next();
					if (item.isFormField()) {
						params.put(item.getFieldName(), item.getString());
					} else {
						imgFileItem = item;
					}
				}
				String action = (String) params.get("action");
				if (action.equals(StringConstants.ADD)) {
					try {
						// create new file img
						String itemName = imgFileItem.getName();
						filename = itemName.substring(itemName
								.lastIndexOf("\\") + 1);
						String realPath = getServletContext().getRealPath("/")
								+ "img\\menu\\" + filename;
						File savedFile = new File(realPath);
						if (!savedFile.exists()) {
							savedFile.createNewFile();
						}
						imgFileItem.write(savedFile);
						filename = savedFile.getName();
					} catch (Exception e) {
						e.printStackTrace();
					}
					// get request parameters
					String name = (String) params.get("name");
					String description = (String) params.get("description");
					int dietId = Integer
							.parseInt((String) params.get("dietId"));
					DietDTO diet = new DietDTO();
					diet.setId(dietId);

					String imgPath = "img\\menu\\" + filename;

					String strCalo = ((String) params.get("calo")).equals("") ? "0"
							: ((String) params.get("calo"));
					int calo = Integer.parseInt(strCalo);

					String strNumberday = ((String) params.get("numberday")) == "" ? "0"
							: ((String) params.get("numberday"));
					int numberday = Integer.parseInt(strNumberday);

					String strNumbermeal = ((String) params.get("numbermeal")) == "" ? "0"
							: ((String) params.get("numbermeal"));
					int numbermeal = Integer.parseInt(strNumbermeal);

					MenuDTO menugroup = new MenuDTO(0, diet, name, description,
							imgPath, calo, numberday, numbermeal);
					MenuDAO dao = new MenuDAO();
					try {
						dao.add(menugroup);
					} catch (Exception e) {
						// delete file img when add fail
						String realPath = getServletContext().getRealPath("/")
								+ "img\\menu\\" + filename;
						File savedFile = new File(realPath);
						savedFile.delete();
						e.printStackTrace();
					}
					response.sendRedirect("MenuServlet");

				} else if (action.equals(StringConstants.EDIT)) {
					// get request parameters
					int id = Integer.parseInt((String) params.get("id"));
					String name = (String) params.get("name");
					String description = (String) params.get("description");
					int dietId = Integer
							.parseInt((String) params.get("dietId"));

					if (imgFileItem.getSize() >= 0) {
						try {
							// if update img, create new file and delete old img
							String itemName = imgFileItem.getName();
							filename = itemName.substring(itemName
									.lastIndexOf("\\") + 1);
							String realPath = getServletContext().getRealPath(
									"/")
									+ "img\\menu\\" + filename;
							File savedFile = new File(realPath);
							imgFileItem.write(savedFile);
							filename = savedFile.getName();

							String oldFilePath = (String) params.get("oldImg");
							realPath = getServletContext().getRealPath("/")
									+ oldFilePath;
							File deletedFile = new File(realPath);
							deletedFile.delete();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					DietDTO diet = new DietDTO();
					diet.setId(dietId);

					String imgPath = "img\\menu\\" + filename;

					String strCalo = ((String) params.get("calo")) == null ? "0"
							: ((String) params.get("calo"));
					int calo = Integer.parseInt(strCalo);

					String strNumberday = ((String) params.get("numberday")) == null ? "0"
							: ((String) params.get("numberday"));
					int numberday = Integer.parseInt(strNumberday);

					String strNumbermeal = ((String) params.get("numbermeal")) == null ? "0"
							: ((String) params.get("numbermeal"));
					int numbermeal = Integer.parseInt(strNumbermeal);

					MenuDTO menugroup = new MenuDTO(id, diet, name,
							description, imgPath, calo, numberday, numbermeal);
					MenuDAO dao = new MenuDAO();

					try {
						dao.update(menugroup);
					} catch (Exception e) {
						// delete file img when update fail
						String realPath = getServletContext().getRealPath("/")
								+ "img\\menu\\" + filename;
						File savedFile = new File(realPath);
						savedFile.delete();

						e.printStackTrace();
					}
					response.sendRedirect("MenuServlet");
				}
			}
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}
	}
}
